<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>数据统计 -- 烟草订单</title>
    <link rel="stylesheet" href="${contextPath}/static/statistics/css/bootstrap.min.css">
    <link rel="stylesheet" href="${contextPath}/static/statistics/css/bootstrap-datetimepicker.min.css">
    <script src="${contextPath}/static/statistics/js/jquery.js"></script>
    <script src="${contextPath}/static/statistics/js/bootstrap.min.js"></script>
    <script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.min.js"></script>
    <script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.fr.js"></script>
    <script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.zh-CN.js"></script>
    <script src="${contextPath}/static/statistics/js/vue.js"></script>
    <script src="${contextPath}/static/statistics/js/echarts.min.js"></script>
    <script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.mockjax.js"></script>
    <script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.autocomplete.js"></script>
    <style>
        .spinner {
            margin: 11px auto 0;
            height: 20px;
            text-align: center;
        }

        .spinner > div {
            width: 10px;
            height: 10px;
            background-color: #67CF22;

            border-radius: 100%;
            display: inline-block;
            -webkit-animation: bouncedelay 1.4s infinite ease-in-out;
            animation: bouncedelay 1.4s infinite ease-in-out;
            /* Prevent first frame from flickering when animation starts */
            -webkit-animation-fill-mode: both;
            animation-fill-mode: both;
        }

        .spinner .bounce1 {
            -webkit-animation-delay: -0.32s;
            animation-delay: -0.32s;
        }

        .spinner .bounce2 {
            -webkit-animation-delay: -0.16s;
            animation-delay: -0.16s;
        }

        @-webkit-keyframes bouncedelay {
            0%, 80%, 100% {
                -webkit-transform: scale(0.0)
            }
            40% {
                -webkit-transform: scale(1.0)
            }
        }

        @keyframes bouncedelay {
            0%, 80%, 100% {
                transform: scale(0.0);
                -webkit-transform: scale(0.0);
            }
            40% {
                transform: scale(1.0);
                -webkit-transform: scale(1.0);
            }
        }

        .autocomplete-suggestions {
            border: 1px solid #999;
            background: #FFF;
            overflow: auto;
        }

        .autocomplete-suggestion {
            padding: 2px 5px;
            white-space: nowrap;
            overflow: hidden;
        }

        .autocomplete-selected {
            background: #F0F0F0;
        }

        .autocomplete-suggestions strong {
            font-weight: normal;
            color: #3399FF;
        }

        @-moz-document url-prefix() {
            fieldset {
                display: table-cell;
            }
        }
    </style>
</head>
<body style="background: rgba(119, 118, 118, 0.15);">
<div class="container-fluid" id="app">
    <div class="row">
        <h4 class="col-sm-6 col-xs-9">烟草订单实时操作数据：</h4>
        <div class="spinner col-sm-6 col-xs-3" style="text-align: right;" title="正在实时获取数据标志">
            <div class="bounce1"></div>
            <div class="bounce2"></div>
            <div class="bounce3"></div>
        </div>
    </div>

    <form class="form-inline" enctype="multipart/form-data" name="myForm">
        <shiro:hasPermission name="CLOUDERPORDERSPLADMINORDER:STATISTICS">
            <div class="form-group">
                <input id="quXianNameInput" class="form-control input-sm" type="text" placeholder="区县名称">
            </div>
        </shiro:hasPermission>
        <shiro:lacksPermission name="CLOUDERPORDERSPLEMPORDER:STATISTICS">
            <shiro:lacksPermission name="CLOUDERPORDERSPLCHANNELORDER:STATISTICS">
            <div class="form-group">
                <input id="channelNameInput" class="form-control input-sm" type="text" placeholder="渠道名称">
            </div>
            </shiro:lacksPermission>
            <div class="form-group">
                <input id="empNameInput" class="form-control input-sm" type="text" placeholder="客户经理名称">
            </div>
        </shiro:lacksPermission>
        <div class="form-group">
            <input id="orderBeginDateInput" type="text" class="form-control input-sm" placeholder="开始可订烟日">
        </div>
        <div class="form-group">
            <input class="form-control input-sm" id="orderEndDateInput" type="text" placeholder="结束可订烟日">
        </div>
        <div class="form-group">
            <input id="custNameId" class="form-control input-sm" type="text" placeholder="专卖证号">
        </div>
        <div class="form-group">
            <input id="orderLevelInput" class="form-control input-sm" type="text" placeholder="档位名称">
        </div>
        <div class="form-group">
            <input id="beginTimeInput" class="form-control input-sm" type="text" placeholder="开始操作时间">
        </div>
        <div class="form-group">
            <input id="endTimeInput" class="form-control input-sm" type="text" placeholder="结束操作时间">
        </div>
        <div class="form-group">
            <input id="orderIdInput" class="form-control input-sm" type="text" placeholder="订单编号">
        </div>
        <div class="form-group">
            <select id="payStatusInput" class="form-control input-sm" type="text" placeholder="支付状态">
                <option value="">--选择支付状态--</option>
                <option value="00">未支付</option>
                <option value="01">支付成功</option>
                <option value="02">付款中</option>
                <option value="99">支付失败</option>
            </select>
        </div>
        <button type="button" class="btn btn-success btn-sm" onclick="selectScratchoff();" title="默认查询近一个月的数据">查询
        </button>
        <button type="button" class="btn  btn-info btn-sm" onclick="exportExcel();" title="导出到Excel">导出</button>
        <button type="button" class="btn btn-warning btn-sm" onclick="autogetData();" title="实时拉取最新的订单数据">实时获取</button>
        <button type="button" class="btn btn-primary btn-sm" onclick="payNoPayOrder();" title="支付未支付的订单">订单支付</button>
        <shiro:hasPermission name="CLOUDERPORDERSPLEMPORDER:STATISTICS">
            <button type="button" class="btn  btn-success btn-sm" onclick="uploadExcelBindCar()" title="上传Excel批量绑卡">
                上传
            </button>
        </shiro:hasPermission>
    </form>
    <div class="table-responsive" id="tableContainer" style="margin-top: 10px;overflow-y: auto">
        <table class="table table-striped table-condensed" >
            <thead style="background-color: rgba(53, 128, 202, 1);">
            <tr style="color: rgb(248, 248, 248);">
                <th>序号</th>
                <th>订单编号</th>
                <!-- <th>订烟时间</th>
                <th>机构代码</th> -->
                <shiro:lacksPermission name="CLOUDERPORDERSPLEMPORDER:STATISTICS">
                    <th>渠道名称</th>

                    <th>客户经理</th>
                </shiro:lacksPermission>
                <th>客户名称</th>
                <th>专卖证号</th>
                <th>电话号码</th>
                <shiro:hasPermission name="CLOUDERPORDERSPLADMINORDER:STATISTICS">
                    <th>类型</th>
                </shiro:hasPermission>
                <th>支付状态</th>
                <th>数量</th>
                <th>金额</th>

                <th>订烟日</th>
                <th>下次订烟日</th>
                <th>操作时间</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(order,index) in orderList">
                <td>{{index+1}}</td>
                <td><a style="color: #00b3ee" href="javascript:void(0);" @click="showOrderProductDetail(order.custCode,order.id)">{{order.id}}</a></td>
                <!-- <td>{{order.orderTimeStr}}</td>
                <td>{{order.channelCode}}</td> -->
                <shiro:lacksPermission name="CLOUDERPORDERSPLEMPORDER:STATISTICS">
                    <td>{{order.channelName}}</td>
                    <td>{{order.slsmanName}}</td>
                </shiro:lacksPermission>
                <td>{{order.custName}}</td>
                <td>{{order.custCode}}</td>
                <td>{{order.createUserPhone}}</td>
                <shiro:hasPermission name="CLOUDERPORDERSPLADMINORDER:STATISTICS">
                    <td>{{order.orderTypeStr}}</td>
                </shiro:hasPermission>
                <td>
                    <input v-show="order.payStatusStr=='未支付' || order.payStatusStr=='支付失败'" v-bind:value="index"
                           v-model="onPayCheckedValues" type="checkbox">
                    <a v-bind:style="'color:'+ (order.payStatusStr=='未支付' ? '#7B3F25' : order.payStatusStr=='支付成功' ? 'green' : order.payStatusStr=='付款中' ? 'blue' : 'red')"
                       href="javascript:void(0);" @click="doPayOrder(index)">{{order.payStatusStr}}</a>

                </td>
                <td>{{order.orderQtySum}}</td>
                <td>{{order.orderAmtSum}}</td>

                <td>{{order.orderTimeStr}}</td>
                <td>{{order.nextOrderTimeStr}}</td>
                <td>{{order.modifiTimeStr}}</td>
            </tr>
            </tbody>
        </table>
    </div>
    <div class="row">
        <div class="col-sm-12 col-xs-12 col-md-4 col-lg-4 main" id="main1" style="margin-top: 10px;"></div>
        <div class="col-sm-12 col-xs-12 col-md-4 col-lg-4 main" id="main3" style="margin-top: 10px;"></div>
        <div class="col-sm-12 col-xs-12 col-md-4 col-lg-4 main" id="main2" style="margin-top: 10px;"></div>
    </div>

    <!-- 订单相关信息modal -->
    <div id="orderDetailContent" class="hide">
        <div class="table-responsive">
            <table class="table table-bordered table-hover table-condensed">
                <thead>
                <tr>
                    <th>序号</th>
                    <th>条码</th>
                    <th>名称</th>
                    <th>单位</th>
                    <th>单价</th>
                    <th>订货量</th>
                    <th>订货金额</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for=" (orderProduct, index) in orderProductList">
                    <td>{{index+1}}</td>
                    <td>{{orderProduct.productCode}}</td>
                    <td>{{orderProduct.productName}}</td>
                    <td>{{orderProduct.unit}}</td>
                    <td>{{orderProduct.price}}</td>
                    <td>{{orderProduct.qty}}</td>
                    <td>{{orderProduct.amt}}</td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>

</div>
<form action="${contextPath}/page/exportExcel" method="post" id="exportExcel" style="display:none">
    <%--<input type="hidden" id="exportExcelData" name="exportExcelData">--%>
    <textarea type="hidden" id="exportExcelData" name="exportExcelData"></textarea>
    <input type="hidden" name="tableType" value="splOrder">
</form>




<!-- 上传文件区域 -->
<div id="uplaodExcelFileContent" style="text-align: center;" class="hide">
    <a style="margin-top: 25px;" href="${contextPath}/page/downLoadExcelTemplate"
       class="btn  btn-success btn-sm">下载模版</a>
    <input  type="file" name="excelInput" style="margin-top: 20px;">
    <button type="button" class="btn  btn-primary btn-sm" onclick="uploadExcel()" title="上传Excel到后台">信息上传</button>
    <div style="margin-top: 30px;">
        <form action="${contextPath}/page/getUploadExcelResult" method="post" id="getUploadExcelResultForm">
            <input style="width:200px;" id="getResultFileNameInput" name="resultFileName" type="text" placeholder="请输入要获取的文件名">
        </form>
    </div>
    <button style="margin-top: 20px;" type="button" class="btn  btn-info btn-sm" onclick="getUploadResult();" title="根据文件名获取上传结果">获取结果</button>
</div>
</body>
<script src=${contextPath}/static/layer/layer.js></script>
<script type="text/javascript">

    var app = new Vue({
        el: '#app',
        data: {
            orderList: [],
            onPayCheckedValues: [],
            orderProductList:[]
        },
        methods: {
            doPayOrder: function (index) {
                var order = this.orderList[index]
                if (order.payStatusStr == '支付成功') {
                    layer.msg('订单已支付成功')
                    return
                }
                if (order.payStatusStr == '付款中') {
                    layer.msg('订单正在付款，请稍后再试')
                    return
                }
                if (order.payStatusStr == '未订烟') {
                    layer.msg('该客户还未订烟')
                    return
                }
                var vm = this
                var indx = layer.confirm('确定要支付本订单吗？', {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    layer.close(indx)
                    layer.load(1)
                    $.ajax({
                        url:  '${contextPath}/supermarket/httpPost',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            url: "http://app1:23912/clouderp-cgt-order-rest/api/cgt/order/autoDk",
                            stringMap: {
                                custCode: order.custCode,
                            }
                        },
                        success: function (data) {
                            layer.closeAll('loading')
                            //console.log(data)
                            if (!data.data) {
                                layer.msg("支付失败")
                                return
                            }
                            layer.msg('支付成功')
                            //修改订单状态
                            order.payStatusStr = '支付成功'
                        }
                        ,
                        error: function (error) {
                            layer.closeAll('loading')
                            layer.msg('网络错误')
                        }
                    });




                    //vm.orderList[index] = order
                }, function () {
                });
            },
            showOrderProductDetail: function (custCode,orderId) {
                if (!orderId || !custCode) {
                    return
                }
                var vm = this
                layer.load(1)
                $.ajax({
                    url:  '${contextPath}/supermarket/httpPost',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        url: "http://app1:23912/clouderp-cgt-order-rest/api/cgt/order/getOrderItem",
                        stringMap: {
                            custCode: custCode,
                            coNum : orderId,
                        }
                    },
                    success: function (data) {
                        layer.closeAll('loading')
                        if (data.code != '000') {
                            layer.msg(data.msg);
                            return
                        }
                        //console.log(data)
                        vm.orderProductList = data.data;
                        $("#orderDetailContent").removeClass("hide")
                        layer.open({
                            type: 1,
                            title: '客户信息',
                            closeBtn: 1,
                            shadeClose: true,
                            maxmin: true,
                            area: ['1100px', '600px'],
                            skin: 'yourclass',
                            content: $("#orderDetailContent"),
                            end: function () {
                                $("#orderDetailContent").addClass("hide")
                            }
                        });

                    }
                    ,
                    error: function (error) {
                        layer.closeAll('loading')
                        layer.msg('网络错误')
                    }
                });
            },

        }

    })


    $(".main").height($(window).height() * 0.55)
    //$("#main1").width($(window).width()*0.3333);
    var myChart1 = echarts.init($("#main1")[0])
    var myChart2 = echarts.init($("#main2")[0])
    var myChart3 = echarts.init($("#main3")[0])

    var option = {
        color: ['#4690F7', '#A3D244', '#1140F2', '#A1F855'],
        title: {
            //text: '最近七天订单统计'
        },
        tooltip: {
            trigger: 'axis'
        },
        toolbox: {
            feature: {
                dataView: {
                    show: false,
                    readOnly: false
                },
                restore: {
                    show: false
                },
                saveAsImage: {
                    show: false
                }
            }
        },
        grid: {
            containLabel: true
        },
        legend: {
            x: 95,
            selected: {
                '支付金额': false,
                '支付订单': false
            },
            data: ['金额', '订单', '支付金额', '支付订单']
        },
        xAxis: [{
            type: 'category',
            axisTick: {
                alignWithLabel: true
            },
            axisLabel: {
                interval: 0,
                rotate: 45,
                show: true,
                splitNumber: 15,
                textStyle: {
                    fontFamily: "微软雅黑",
                    fontSize: 12
                }
            },
            data: []
        }],
        yAxis: [{
            type: 'value',
            name: '金额',
            position: 'right',
            axisLabel: {
                formatter: '{value} 万元'
            }
        }, {
            type: 'value',
            name: '订单',
            position: 'left',
            axisLabel: {
                formatter: '{value} 笔'
            }
        }],
        series: [{
            name: '金额',
            type: 'line',
            label: {
                normal: {
                    show: true,
                    position: 'top',
                }
            },
            data: []
        }, {
            name: '订单',
            type: 'line',
            yAxisIndex: 1,
            label: {
                normal: {
                    show: true,
                    position: 'top',
                }
            },
            data: []
        }]
    };
    // 使用刚指定的配置项和数据显示图表。
    myChart1.setOption(option)
    myChart2.setOption(option)
    myChart3.setOption(option)

    var changeData = function (orderArray) {
        //var appData = app.orderList;
        //console.log(appData)
        //appData.pop();
        app.orderList.unshift(orderArray)

        /* {
         orderNo : 'FDS34324-0',
         modifiTimeStr : '2016-12-11 18:18:18',
         jigouCode : '9807899700',
         jigouName : '健康的',
         kehujinli: '你色即是空',
         custCode : '23132133',
         orderType : '43',
         payStatus : '支付失败',
         number : '43',
         price : '8930.23'
         }*/
        //app.orderList = appData
    }

    var countNum = 1;
    var intervalGetOrder = function () {

        var order = app.orderList[0]
        var lastCreateTime = ""
        if (order) {
            lastCreateTime = order.modifiTimeStr;
        }
        //var lastCreateTime = "2017-01-11 18:18:18"
        //console.log(lastCreateTime)
        //console.log('第' + (countNum++) + '次获取数据')
        $.ajax({
            url: '${contextPath}/page/getOrder', //localhost:8080
            type: 'post',
            data: {
                lastOrderTime: lastCreateTime,
            },
            success: function (data) {
                if (data.success) {
                    var dataArray = data.data.SPLOrderList

                    if (dataArray.length > 0 && (countNum != 2 || <shiro:hasPermission name="CLOUDERPORDERSPLEMPORDER:STATISTICS">false</shiro:hasPermission><shiro:lacksPermission name="CLOUDERPORDERSPLEMPORDER:STATISTICS">true</shiro:lacksPermission>)) {
                        if (order) {
                            var newOrder = dataArray[dataArray.length - 1]
                            if (order.id == newOrder.id && order.payStatusStr == '支付成功' && newOrder.payStatusStr == '支付成功') {
                                dataArray.pop()
                            }
                        }


                        var appOrderList = dataArray.concat(app.orderList)

                        if (appOrderList.length > 50) {
                            appOrderList = appOrderList.slice(0, 51)
                        }

                        var lastData = appOrderList[appOrderList.length - 1]
                        if (lastData.id == "合计：") {
                            appOrderList.pop();
                        }
                        var numTotal = {};
                        numTotal.id = "合计："
                        var orderQtySum = 0;
                        var orderAmtSum = 0;
                        for (index in appOrderList) {
                           // console.log(appOrderList)
                            orderQtySum = numAdd(appOrderList[index].orderQtySum, orderQtySum);
                            orderAmtSum = numAdd(appOrderList[index].orderAmtSum, orderAmtSum);
                        }
                        numTotal.orderQtySum = orderQtySum
                        numTotal.orderAmtSum = orderAmtSum
                        appOrderList.push(numTotal)
                        app.orderList = appOrderList
                    }

                    //console.log(data.data.SPLOrderDayData)
                    var SPLOrderDayDataObj = data.data.SPLOrderDayData;
                    var SPLOrderMonthDataObj = data.data.SPLOrderMonthData;
                    var SPLOrderYearDataObj = data.data.SPLOrderYearData;

                    var successSPLOrderDayDataObj = data.data.successSPLOrderDayData;
                    var successSPLOrderMonthDataObj = data.data.successSPLOrderMonthData;
                    var successSPLOrderYearDataObj = data.data.successSPLOrderYearData;

                    if (SPLOrderDayDataObj != null) {
                        updateOrderDayData(SPLOrderDayDataObj, successSPLOrderDayDataObj)
                        updateOrderMonthData(SPLOrderMonthDataObj, successSPLOrderMonthDataObj)
                        updateOrderYearData(SPLOrderYearDataObj, successSPLOrderYearDataObj)
                    }
                    //console.log('数据长度为：' + dataArray.length)
                } else if (data.success == undefined) {
                    window.location.href = "${contextPath}"
                }
                //console.log(data.data)

            },
            error: function (error) {
                //console.log(error)
            }
        })
    }

    var intervalId;
    intervalId = setInterval(intervalGetOrder, "10000");


    $("#tableContainer").css("border", "1px solid gray");
    //改变div的高度
    $("#tableContainer").height($(window).height() * 0.35);

    function updateOrderDayData(data, successData) {
        var xDatas = data.dayNums
        var successDatas = successData.dayNums

        var successPriceSums = successData.priceSums;
        var realSuccessPriceSums = []

        var successCountNums = successData.countNums
        var realSuccessCountNums = []

        for (var i = 0; i < xDatas.length; i++) {

            var index = $.inArray(xDatas[i], successDatas);
            if (index == -1) {
                realSuccessPriceSums[i] = 0;
                realSuccessCountNums[i] = 0;
            } else {
                realSuccessPriceSums[i] = successPriceSums[index]
                realSuccessCountNums[i] = successCountNums[index]
            }
        }

        myChart1.setOption({
            title: {
                text: '天趋势统计'
            },
            xAxis: {
                data: data.dayNums
            },
            series: [{
                // 根据名字对应到相应的系列
                name: '金额',
                type: 'line',
                lineStyle: {
                    normal: {
                        width: 3,
                        shadowColor: 'rgba(0,0,0,0.4)',
                        shadowBlur: 10,
                        shadowOffsetY: 10
                    }
                },
                data: data.priceSums
            }, {
                name: '订单',
                type: 'line',
                lineStyle: {
                    normal: {
                        width: 3,
                        shadowColor: 'rgba(0,0,0,0.4)',
                        shadowBlur: 10,
                        shadowOffsetY: 10
                    }
                },
                data: data.countNums
            }, {
                // 根据名字对应到相应的系列
                name: '支付金额',
                type: 'line',
                lineStyle: {
                    normal: {
                        width: 3,
                        shadowColor: 'rgba(0,0,0,0.4)',
                        shadowBlur: 10,
                        shadowOffsetY: 10
                    }
                },
                data: realSuccessPriceSums
            }, {
                name: '支付订单',
                type: 'line',
                lineStyle: {
                    normal: {
                        width: 3,
                        shadowColor: 'rgba(0,0,0,0.4)',
                        shadowBlur: 10,
                        shadowOffsetY: 10
                    }
                },
                data: realSuccessCountNums
            }]
        });

    }

    function updateOrderMonthData(data, successData) {
        //巧妙解决单个记录只有支付失败的订单的情况，没有成功订单的话设置为0
        var xDatas = data.dayNums
        var successDatas = successData.dayNums

        var successPriceSums = successData.priceSums;
        var realSuccessPriceSums = []

        var successCountNums = successData.countNums
        var realSuccessCountNums = []

        for (var i = 0; i < xDatas.length; i++) {

            var index = $.inArray(xDatas[i], successDatas);
            if (index == -1) {
                realSuccessPriceSums[i] = 0;
                realSuccessCountNums[i] = 0;
            } else {
                realSuccessPriceSums[i] = successPriceSums[index]
                realSuccessCountNums[i] = successCountNums[index]
            }
        }
        myChart2.setOption({
            title: {
                text: '月趋势统计'
            },
            xAxis: {
                data: data.dayNums
            },
            series: [{
                // 根据名字对应到相应的系列
                name: '金额',
                type: 'bar',
                label: {
                    normal: {
                        show: true,
                        position: 'top',
                    }
                },
                data: data.priceSums
            }, {
                // 根据名字对应到相应的系列
                name: '订单',
                type: 'bar',
                yAxisIndex: 1,
                label: {
                    normal: {
                        show: true,
                        position: 'top',
                    }
                },
                data: data.countNums
            }, {
                // 根据名字对应到相应的系列
                name: '支付金额',
                type: 'bar',
                label: {
                    normal: {
                        show: true,
                        position: 'top',
                    }
                },
                data: realSuccessPriceSums
            }, {
                // 根据名字对应到相应的系列
                name: '支付订单',
                type: 'bar',
                yAxisIndex: 1,
                label: {
                    normal: {
                        show: true,
                        position: 'top',
                    }
                },
                data: realSuccessCountNums
            }]
        });

    }

    function updateOrderYearData(data, successData) {

        var xDatas = data.dayNums
        var successDatas = successData.dayNums

        var successPriceSums = successData.priceSums;
        var realSuccessPriceSums = []

        var successCountNums = successData.countNums
        var realSuccessCountNums = []

        for (var i = 0; i < xDatas.length; i++) {

            var index = $.inArray(xDatas[i], successDatas);
            if (index == -1) {
                realSuccessPriceSums[i] = 0;
                realSuccessCountNums[i] = 0;
            } else {
                realSuccessPriceSums[i] = successPriceSums[index]
                realSuccessCountNums[i] = successCountNums[index]
            }
        }
        myChart3.setOption({
            title: {
                text: '周趋势统计'
            },
            xAxis: {
                data: data.dayNums
            },
            series: [{
                // 根据名字对应到相应的系列
                name: '金额',
                type: 'line',
                lineStyle: {
                    normal: {
                        width: 3,
                        shadowColor: 'rgba(0,0,0,0.4)',
                        shadowBlur: 10,
                        shadowOffsetY: 10
                    }
                },
                data: data.priceSums
            }, {
                // 根据名字对应到相应的系列
                name: '订单',
                type: 'bar',
                yAxisIndex: 1,
                label: {
                    normal: {
                        show: true,
                        position: 'top',
                    }
                },
                data: data.countNums
            }, {
                // 根据名字对应到相应的系列
                name: '支付金额',
                type: 'line',
                lineStyle: {
                    normal: {
                        width: 3,
                        shadowColor: 'rgba(0,0,0,0.4)',
                        shadowBlur: 10,
                        shadowOffsetY: 10
                    }
                },
                data: realSuccessPriceSums
            }, {
                // 根据名字对应到相应的系列
                name: '支付订单',
                type: 'bar',
                yAxisIndex: 1,
                label: {
                    normal: {
                        show: true,
                        position: 'top',
                    }
                },
                data: realSuccessCountNums
            }]
        });

    }
    intervalGetOrder()
    //var nowDate = new Date();
    //nowDate.setMonth(nowDate.getMonth() - 1);
    $('#beginTimeInput').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        //startDate: nowDate,
    }).on('changeDate', function (e) {
        var startTime = e.date;
        $('#endTimeInput').datetimepicker('setStartDate', startTime);
    });
    $('#endTimeInput').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1
    }).on('changeDate', function (e) {
        var endTime = e.date;
        $('#beginTimeInput').datetimepicker('setEndDate', endTime);
    });

    $('#orderBeginDateInput').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        format: "yyyymmdd",
        //startDate:new Date(),
    });
    $('#orderEndDateInput').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        format: "yyyymmdd",
        //startDate:new Date(),
    });


    var selectScratchoff = function () {
        var quXianName = $("#quXianNameInput").val();
        var channelName = $("#channelNameInput").val();
        var empName = $("#empNameInput").val();
        var orderBeginDate = $("#orderBeginDateInput").val();
        var orderEndDate = $("#orderEndDateInput").val();
        var custName = $("#custNameId").val();
        var beginTime = $("#beginTimeInput").val();
        var endTime = $("#endTimeInput").val();
        var payStatus = $("#payStatusInput").val();
        var orderId = $("#orderIdInput").val();
        var orderLevel = $("#orderLevelInput").val();
        if (orderId == "" && quXianName == "" && channelName == "" && beginTime == "" && endTime == "" && custName == "" && empName == "" && orderBeginDate == "" && orderEndDate == "" && payStatus == ""  && orderLevel=="") {
            layer.msg("请至少选择一个查询条件")
            return
        }
        layer.load(1)
        $.ajax({
            url: '${contextPath}/page/getOrderByTime',
            type: 'post',
            dataType: 'json',
            data: {
                quXianName: quXianName,
                channelName: channelName,
                beginTime: beginTime,
                endTime: endTime,
                custName: custName,
                empName: empName,
                orderBeginDate: orderBeginDate,
                orderEndDate: orderEndDate,
                payStatus: payStatus,
                orderId:orderId,
                orderLevel : orderLevel,
            },
            success: function (data) {
                if (data.success) {
                    var array = data.data;
                    if (array.length > 0) {
                        clearInterval(intervalId)

                        var numTotal = {};
                        numTotal.id = "合计："+ array.length + "笔"
                        var orderQtySum = 0;
                        var orderAmtSum = 0;
                        for (index in array) {
                            // console.log(array)
                            orderQtySum = numAdd(array[index].orderQtySum, orderQtySum);
                            orderAmtSum = numAdd(array[index].orderAmtSum, orderAmtSum);
                        }
                        numTotal.orderQtySum = orderQtySum
                        numTotal.orderAmtSum = orderAmtSum
                        array.unshift(numTotal)

                        app.orderList = array
                        $(".spinner").addClass("hide")
                    } else {
                        layer.msg("所选条件没有数据")
                    }
                } else {
                    layer.msg(data.message);
                }
                layer.closeAll('loading')
            },
            error: function (error) {
                layer.closeAll('loading')
                layer.msg("网络连接失败")
            }
        })
    }

    var autogetData = function () {
        if ($(".spinner").hasClass("hide") == false) {
            layer.msg("已经在实时获取数据")
            return
        }
        intervalId = setInterval(intervalGetOrder, "10000");
        $(".spinner").removeClass("hide")
    }


    var exportExcel = function () {
        if (app.orderList.length <= 0) {
            layer.msg("当前表格没有数据");
            return
        }
        $("#exportExcelData").val(JSON.stringify(app.orderList))
        $("#exportExcel").submit();

    }

    function numAdd(num1, num2) {
        if (num1 == null || num1 == undefined || num1 == "") {
            return num2;
        }
        var baseNum, baseNum1, baseNum2;
        try {
            baseNum1 = num1.toString().split(".")[1].length;
        } catch (e) {
            baseNum1 = 0;
        }
        try {
            baseNum2 = num2.toString().split(".")[1].length;
        } catch (e) {
            baseNum2 = 0;
        }
        baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
        var precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;//精度
        return ((num1 * baseNum + num2 * baseNum) / baseNum).toFixed(precision);
        ;
    };

    var formatDate = function (data) {
        if (data < 10) {
            data = "0" + data
        }
        return data
    }
    <shiro:hasPermission name="CLOUDERPORDERSPLEMPORDER:STATISTICS">
    var date = new Date()
    $("#orderBeginDateInput").val(date.getFullYear() + '' + formatDate(date.getMonth() + 1) + '' + formatDate(date.getDate()));

    var endDate = new Date()
    endDate.setTime(endDate.getTime() + 24 * 60 * 60 * 1000)
    $("#orderEndDateInput").val(endDate.getFullYear() + '' + formatDate(endDate.getMonth() + 1) + '' + formatDate(endDate.getDate()))
    selectScratchoff()

    </shiro:hasPermission>

    <shiro:lacksPermission name="CLOUDERPORDERSPLEMPORDER:STATISTICS">

    var selectEmpNameToSelected = function (channelName) {
        $.ajax({
            url: '${contextPath}/checking/selectEmpNameToSelected?channelName=' + channelName,
            success: function (data) {
                if (data.success) {
                    var countries = data.data
                    $('#empNameInput').autocomplete({
                        lookup: countries,
                        onSelect: function (suggestion) {
                            //console.log('You selected: ' + suggestion.value + ', ' + suggestion.data);
                        },
                        width: 200,
                        minChars: 0,
                    });
                }
            }
        })
    }
    selectEmpNameToSelected('')

    var selectChannelNameToSelected = function (quXianName) {
        $.ajax({
            url: '${contextPath}/checking/selectChannelNameToSelected?quXianName=' + quXianName,
            success: function (data) {
                if (data.success) {
                    var countries = data.data
                    $('#channelNameInput').autocomplete({
                        lookup: countries,
                        onSelect: function (suggestion) {
                            //alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                            selectEmpNameToSelected(suggestion.value)
                        },
                        width: 200,
                        minChars: 0,
                    });
                }
            }
        })
    }
    selectChannelNameToSelected('')
    <shiro:hasPermission name="CLOUDERPORDERSPLADMINORDER:STATISTICS">
    $.ajax({
        url: '${contextPath}/checking/selectQuXianNameToSelected',
        success: function (data) {
            if (data.success) {
                var countries = data.data
                $('#quXianNameInput').autocomplete({
                    lookup: countries,
                    onSelect: function (suggestion) {
                        //alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                        selectChannelNameToSelected(suggestion.value)
                    },
                    width: 200,
                    minChars: 0,
                });
            }
        }
    })
    </shiro:hasPermission>
    </shiro:lacksPermission>

    $(function () {
        $('[data-toggle="tooltip"]').tooltip()
    })

    var uploadExcelBindCar = function () {
        $("#uplaodExcelFileContent").removeClass("hide")
        this.payQrCodeModalId = layer.open({
            type: 1,
            title: '上传客户信息文件',
            closeBtn: 1,
            area: ['300px', '300px'],
            skin: 'yourclass',
            content: $("#uplaodExcelFileContent"),
            end: function () {
                $("#uplaodExcelFileContent").addClass("hide")
            }
        });
    }
    


    var uploadExcel = function () {
        var excel = $("[name = 'excelInput']:input")[0].files[0];

        //console.log(excel.name.substr(excel.name.lastIndexOf('.')))
        //console.log(excel.size)

        if (excel == undefined) {
            layer.msg("请选择excel文件")
            return
        }
        if (excel.name.substr(excel.name.lastIndexOf('.')) != '.xls') {
            layer.msg("选择的文件不是excel类型")
            return
        }
        if (excel.size > 1048576) {
            layer.msg("选择的excel大于1Mb")
            return
        }
        var fm = new FormData();
        fm.append('excel', excel);
        layer.load(1)
        $.ajax(
            {
                url: '${contextPath}/page/uploadExcel',
                type: 'POST',
                data: fm,
                contentType: false, //禁止设置请求类型
                processData: false, //禁止jquery对DAta数据的处理,默认会处理
                //禁止的原因是,FormData已经帮我们做了处理
                success: function (data) {
                    //测试是否成功
                    //但需要你后端有返回值
                    //console.log(data);
                    if (data.success) {
                        //console.log(data.data);
                        $('#getResultFileNameInput').val(data.data)
                        layer.msg('上传成功--请保存文件名，稍后获取结果');
                    } else {
                        layer.msg('上传失败，稍后再试');
                    }
                    layer.closeAll('loading')
                },
                error: function (error) {
                    layer.msg("网络连接失败");
                    layer.closeAll('loading')
                }
            }
        );
    }


    var getUploadResult = function () {
        var fileName = $('#getResultFileNameInput').val();
        if(fileName == "") {
            layer.msg("请输入要获取的文件名称")
            $('#getResultFileNameInput').focus()
            return
        }

        if (fileName.substr(fileName.lastIndexOf('.')) != '.xls') {
            layer.msg("要获取的文件名称不对，请确认输入")
            $('#getResultFileNameInput').focus()
            return
        }
        layer.load(1)
        $.ajax(
            {
                url: '${contextPath}/page/examineUploadExcelResultIsExists',
                type: 'POST',
                data: {
                    resultFileName : fileName,
                },
                dataType : 'json',
                success: function (data) {
                    layer.closeAll('loading')
                    if (!data.success) {
                        layer.msg('文件没有找到或者正在处理，请稍后再试');
                    } else {
                        $('#getUploadExcelResultForm').submit()
                    }

                },
                error: function (error) {
                    //console.log(error)
                    layer.msg("网络连接失败");
                    layer.closeAll('loading')
                }
            }
        );
    }

    var payNoPayOrder = function () {
        if (app.onPayCheckedValues.length == 0) {
            layer.msg("没有选择未支付订单");
            return;
        }
        var orders = [];
        $(app.onPayCheckedValues).each(function (key, val) {
            orders.push(app.orderList[val]);
        })
        var indx = layer.confirm('确定要支付选择的' + app.onPayCheckedValues.length + '条订单吗？', {
            btn: ['确定', '取消'] //按钮
        }, function () {

            layer.close(indx)
            app.onPayCheckedValues = []
            var successOrderCount = 0;
            layer.load(1)
            //修改订单状态
            $(orders).each(function (key, value) {
                $.ajax({
                    url: '${contextPath}/supermarket/httpPost',
                    type: 'post',
                    dataType: 'json',
                    async : false,
                    data: {
                        url: "http://app1:23912/clouderp-cgt-order-rest/api/cgt/order/autoDk",
                        stringMap: {
                            custCode: value.custCode,
                        }
                    },
                    success: function (data) {
                        //console.log(data)
                        if (!data.data) {
                            return
                        }
                        //修改订单状态
                        value.payStatusStr = '支付成功'
                        successOrderCount +=1;
                    }
                    ,
                    error: function (error) {
                    }
                });


            })
            layer.closeAll('loading')
            layer.msg("成功支付："+successOrderCount +"条订单")

        }, function () {
        });
    }

    var selectOrderLevelToSelected = function () {
        $.ajax({
            url: '${contextPath}/checking/selectOrderLevelToSelected',
            success: function (data) {
                if (data.success) {
                    var countries = data.data
                    $('#orderLevelInput').autocomplete({
                        lookup: countries,
                        onSelect: function (suggestion) {
                            //console.log('You selected: ' + suggestion.value + ', ' + suggestion.data);
                        },
                        //width: 200,
                        minChars: 0,
                    });
                }
            }
        })
    };
    selectOrderLevelToSelected();
</script>
</html>





